//按钮用于移除全部附件
var removeAttachedButton = Ext.create('Ext.Button', {
    text: "移除全部附件",
    handler: function () {
        attachedStore.removeAll();
    }
});

//任务表单
var taskForm = Ext.create('Ext.form.Panel', {
    //xtype: 'form',
    id: 'taskForm',
    title: '编辑任务',
    frame: true,
    scrollable: true, //大小溢出时自动出现滚动条
    bodyPadding: '10 20',
    defaults: {
        anchor: '98%',
        msgTarget: 'side',
        allowBlank: false
    },
    items: [
        {
            fieldLabel: '任务名称',
            xtype: 'textfield',
            id: 'taskName',
            emptyText: '限制字数' + fieldWordLimited,
            maxLength: fieldWordLimited
        },
        {
            fieldLabel: '以组接受任务',
            id: 'isGroup',
            xtype: 'radiogroup',
            columns: [100, 100],
            items: [{boxLabel: '是', name: 'isGroup', inputValue: 1, itemId: 'yes'}, {
                boxLabel: '否',
                name: 'isGroup',
                inputValue: 0,
                itemId: 'no',
                checked: true
            }],
            listeners: {//监听收件人类别改变收件人列表
                change: function (radio, newValue, oldValue, eOpts) {
                    if (newValue.isGroup == 0) {
                        taskForm.down('#chooseReceiver').setFieldLabel('收件人');
                        chooseReceiverGrid.setStore(Ext.data.StoreManager.lookup('receiversStore'));
                        Ext.data.StoreManager.lookup('receiversStore').reload();
                        taskForm.down('#chooseReceiver').setValue();
                    } else {
                        taskForm.down('#chooseReceiver').setFieldLabel('收件组');
                        chooseReceiverGrid.setStore(Ext.data.StoreManager.lookup('receiversGroupStore'));
                        Ext.data.StoreManager.lookup('receiversGroupStore').reload();
                        taskForm.down('#chooseReceiver').setValue();
                    }
                }
            }
        },
        {
            xtype: 'panel',
            border: false,
            layout: 'hbox',
            margin: '0 0 5 0',
            items: [{
                xtype: 'textfield',
                itemId: 'chooseReceiver',
                allowBlank: false,
                fieldLabel: '收件人',
                emptyText: '请选择',
                editable: false//防止用户直接在文本框里输入
            }, {
                xtype: 'button',
                text: '选择',
                margin: '0 0 0 10',
                listeners: [{
                    click: function () {
                        chooseReciverGridWin.show();
                    }
                }]
            }],
//                editable: false,//防止用户直接在下拉框里输入
//                id: 'taskReceiverId',
//                emptyText: '到时候会从后台获取所有可以派发任务的用户名单和用户组名',
//                store: receiverUserStore,
//                queryMode: 'local',
//                displayField: 'receiverName',
//                valueField: 'receiverId',
        },
        {
            fieldLabel: '任务描述',
            xtype: 'textareafield',
            id: 'taskDescription',
            cls: 'x-form-valid',
            emptyText: '填写任务描述'
        },
        {
            fieldLabel: '任务类型',
            xtype: 'combo',
            editable: false,//防止用户直接在下拉框里输入
            id: 'taskType',
            emptyText: '选择任务类型',
            store: typeStore,
            queryMode: 'local',
            displayField: 'typeName',
            valueField: 'typeNum',
        },
        {
            fieldLabel: '任务优先级',
            xtype: 'combo',
            editable: false,//防止用户直接在下拉框里输入
            id: 'taskPriority',
            emptyText: '选择任务优先级',
            store: priorityStore,
            queryMode: 'local',
            displayField: 'priorityName',
            valueField: 'priorityNum',
        },
        {
            xtype: 'fieldset',
            itemId: 'taskFormAttachFieldset',
            title: '是否添加附件',
            collapsed: true,//设定展开状态初始为不展开
            checkboxToggle: true,
            padding: 20,
            items: [
                {
                    xtype: 'form',
                    title: '上传任务附件',
                    id: 'attachedUploadFiel',
                    layout: 'fit',//再布局
                    bodyPadding: 10,
                    frame: true,//边框圆润一点
                    items: [{
                        xtype: 'filefield',
                        name: 'file',
                        fieldLabel: '附件',
                        labelWidth: 30,
                        msgTarget: 'side',
                        fileUpload: true,
                        allowBlank: false,
                        anchor: '100%',
//                            maxWidth:900,
//                            buttonConfig:{
//                            	text:'选择文件路径',
//                            	margin:'0 100 0 10'
//                            },
                        buttonText: '选择文件路径',
                        validator: function (value) {
                            if (value != "") {
                                //将文件名用”.”区分，取最后一部分来判断后缀
                                taskFileName = value.substring(value.lastIndexOf('\\') + 1);//取文件最后的名字来储存文件名字
                                var arr = value.split('.');
                                // 判断是不是图片类型的文件两种格式均可
                                if (arr[arr.length - 1].toLowerCase() == 'jpg'
                                    || arr[arr.length - 1].toLowerCase() == 'png'
                                    || arr[arr.length - 1].toLowerCase() == 'gif'
                                    || arr[arr.length - 1].toLowerCase() == 'jpeg') {
                                    taskFileType = 0;
                                } else {
                                    taskFileType = 1;
                                }
                                return true;
                            }
                        }
                    },
                        {
                            xtype: 'grid',
                            store: attachedStore,
                            layout: 'fit',//再布局
                            stateful: true,
                            stateId: 'stateGrid',
                            frame: true,//边框圆润一点
                            columns: [
                                {
                                    text: '附件名称',
                                    flex: 1,
                                    sortable: false,
                                    dataIndex: 'attachedName'
                                },
                                {
                                    text: '附件类型',
                                    flex: 1,
                                    sortable: false,
                                    dataIndex: 'fileType',
                                    hidden: true
                                },
                                {
                                    xtype: 'actioncolumn',
                                    width: 50,
                                    items: [{
                                        icon: 'static/images/icons/fam/delete.gif',  // Use a URL in the icon config
                                        tooltip: '删除该附件',
                                        handler: function (grid, rowIndex, colIndex) {
                                            attachedStore.removeAt(rowIndex);
                                        }
                                    }]
                                }
                            ],
                            height: 200,
                            width: 400,
                            margin: '10 0 20 0',
                            title: '附件列表',
                            renderTo: document.body,
                            viewConfig: {
                                stripeRows: true
                            },
                            bbar: [removeAttachedButton]
                        }
                    ],
                    buttons: [{
                        text: '上传',
                        buttonAlign: 'center',
                        handler: function (value) {
                            var msg = new Ext.window.MessageBox();
                            msg.wait('正在上传中...');
                            var form = this.up('form').getForm();
                            var fileEl = form.findField('file').fileInputEl.dom;
                            var fd = new FormData();
                            fd.append("file", fileEl.files[0]);
                            fd.append("fileType", taskFileType);
                            Ext.Ajax.request({
                                url: zuulUrl + '/' + taskServiceName + '/uploadAttached',
                                async: true,   //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
                                method: 'post',
                                rawData: fd,
                                headers: {
                                    "Content-Type": null   /* 最重要的部分，将Content-Type设置成null，ExtJs则会由内部的XMLHTTPRequest自动生成包含boundary的Content-Type，否则在使用rawData的情况下，ExtJs会将Content-Type设置成text/plain */
                                },
                                success: function (response, opts) {
                                    var obj = response.responseText;
                                    var fileUuid = obj;
                                    var taskAttachedId = Ext.create("MyApp.data.MyModelX").data.id.replace(/-/g, "");//生成任务附件链接Id
                                    var record = {
                                        id: taskAttachedId,
                                        uuid: fileUuid,
                                        attachedName: taskFileName,
                                        fileType: taskFileType
                                    };
                                    attachedStore.insert(0, record);
                                    Ext.Msg.alert('Success', '上传成功');
                                },
                                failure: function (response, opts) {
                                    Ext.Msg.alert('Error', '该功能暂时不可用');
                                }
                            });
                            msg.close();

//                            	var form=taskForm.getForm();
//                                    form.submit({
//                                        method: 'post',
//                                        enctype: "multipart/form-data",
//                                        url: 'http://192.168.32.254:8761/task/uploadAttached?fileType=' + taskFileType,
//                                        waitMsg: '正在上传中...',
//                                        success: function (msg, data) {
//                                            console.log(data.result.fileName);
//                                            var jsonArray = new Array();
//                                            var object = new Object();
//                                            taskAttachedId=Ext.create("MyApp.data.MyModelX").data.id.replace(/-/g,"");//生成任务附件链接Id
//                                            object['id'] = taskAttachedId;
//                                            object['name'] = taskFileName;
//                                            object['taskId'] = taskId;
//                                            object['FileUuid'] = data.result.fileName;
//                                            object['HashOrUuid'] = taskFileType;
//                                            jsonArray.push(object);
//                                            var json = Ext.JSON.encode(jsonArray);
//                                            Ext.Ajax.request({
//                                                url: 'http://192.168.32.254:8761/task/addAttached',
//                                                async: true,   //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
//                                                method: 'post',
//                                                params: {
//                                                    json: json
//                                                },
//                                                success: function (response, opts) {
//                                                	var record={TA_ATTACHED_ID:taskAttachedId,TA_UUID:data.result.fileName,TA_ATTACHED_NAME:taskFileName,TA_HASHORUUID:taskFileType};
//                                                	attachedStore.insert(0,record);
//                                                	Ext.Msg.alert('Success', '上传成功');
//                                                },
//                                                failure: function (response, opts) {
//                                                    console.log('server-side failure with status code ' + response.status);
//                                                }
//                                            });
//                                        },
//                                        failure: function (form, action) {
//                                            console.info(action);
//                                            switch (action.failureType) {
//                                                case Ext.form.Action.CLIENT_INVALID:
//                                                    Ext.Msg.alert('失败', '所填的值的类型不正确');
//                                                    break;
//                                                case Ext.form.Action.CONNECT_FAILURE:
//                                                    Ext.Msg.alert('失败', '连接服务器失败');
//                                                    break;
//                                                case Ext.form.Action.SERVER_INVALID:
//                                                    Ext.Msg.alert('失败', '服务器故障');
//                                            }
//                                        }
//                                    });
                        }
                    }]
                }
            ]
        }
    ],

    buttons: [
        {
            text: '保存并发布',
            id: 'saveAndSendTaskButton',
            handler: function (button) {
                taskSaveOrCommit(true);
            }
        },
        {
            text: '保存',
            id: 'saveTaskButton',
            handler: function () {
                taskSaveOrCommit(false);
            }
        },
        {
            text: '清空表单',
            id: 'resertTaskForm',
            handler: function () {
                Ext.getCmp('taskForm').getForm().reset();
            }
        }
    ]
});